from sockets.frontsocket import sio
from sockets.agvsocket import AgvSocket

from settings.settings import settings

from role.admin import Admin

sio_manage = AgvSocket()
sio_config = sio_manage.get(settings.AGV_PORT_CONFIG)


async def init_config_event():
    await init_control_lock()


async def init_control_lock():
    @sio.on('seizecontrol')
    async def control(sid, timestamp):
        # 设置当前的agv的控制者
        cachesid = Admin().set_admin(sid)
        if cachesid:
            await sio.emit('losecontrol', to=cachesid)
        await sio.emit('seizecontrol', True, to=sid)

    @sio.on('releasecontrol')
    async def release(sid, timestamp):
        # 设置当前的agv的控制者
        flag = Admin().release_admin(sid)

        if (flag == 'success'):
            await sio.emit('releasecontrol', 'success', to=sid)
        else:
            await sio.emit('releasecontrol', 'fail', to=sid)
